﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AjaxPro
{
    /// <summary>
    /// 使用Json.net为对象进行JSON字符串的序列化和反序列化
    /// </summary>
    public class JsonSerialize
    {
        #region Json序列化和反序列化

        /// <summary>
        /// 序列化对象为Json字符串
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>Json字符串</returns>
        public static string SerializeToJson(object obj)
        {
            Newtonsoft.Json.Converters.IsoDateTimeConverter isoDateTimeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj, isoDateTimeConverter);
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="value">Json字符串</param>
        /// <returns>目标类型的实例</returns>
        public static T DeserializeFromJson<T>(string value)
        {
            Newtonsoft.Json.Converters.IsoDateTimeConverter isoDateTimeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value, isoDateTimeConverter);
        }

        public static object DeserializeFromJson(string value, Type type)
        {
            Newtonsoft.Json.Converters.IsoDateTimeConverter isoDateTimeConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
            return Newtonsoft.Json.JsonConvert.DeserializeObject(value, type, isoDateTimeConverter);
        }

        #endregion
    }
}
